package com.useeinfo.oa.open.dashboard.security;

import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.action.BaseAction;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.tools.CommonSugar;
import com.useeinfo.framework.sugar.tools.ResultJson;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.EnterpriseBiz;
import com.useeinfo.oa.modules.base.biz.PositionBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Organization;
import com.useeinfo.oa.modules.base.entity.Position;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemAuthorityBiz;
import com.useeinfo.oa.modules.security.biz.SystemRoleBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemAuthority;
import com.useeinfo.oa.modules.security.entity.SystemRole;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Author: 居泽平
 */
@Controller
@RequestMapping("/web/admin/systemRole")
public class SystemRoleAction extends BaseAction {

    @Autowired
    private SystemRoleBiz systemRoleBiz;
    @Autowired
    private SystemUserBiz systemUserBiz;
    @Autowired
    private SystemAuthorityBiz systemAuthorityBiz;
    @Autowired
    private EnterpriseBiz enterpriseBiz;
    @Autowired
    private OrganizationBiz organizationBiz;
    @Autowired
    private PositionBiz positionBiz;
    @Autowired
    private HttpServletRequest request;

    // ******************************************************************************
    // ******************************* 代码自动生成开始 *******************************
    // ******************************************************************************

    /**
     * 打开列表页面
     */
    @RequestMapping("/getSystemRoleListPage")
    public ModelAndView getSystemRoleListPage() {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/system/systemRole/systemRoleList");

        return modelAndView;
    }

    /**
     * 分页获取JSON数据
     */
    @RequestMapping("/getSystemRoleListJSON")
    @ResponseBody
    public JSONObject getSystemRoleListJSON(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                                            @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                                            @RequestParam(value = "orderBy", required = false) String orderBy,
                                            @RequestParam(value = "searchCode", required = false) String searchCode,
                                            HttpServletRequest request) {

        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        queryParam.getSqlMap().put("searchCode", searchCode);
        Enterprise enterprise = CommonSugar.getTypedDefault(SessionKeyUtils.getSessionEnterprise(request), new Enterprise());
        queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        if (StringUtils.isNotBlank(orderBy))
            queryParam.setSqlOrder("order by " + orderBy);
        return systemRoleBiz.findJSONList(queryParam);
    }

    /**
     * 获取分配页面
     */
    @RequestMapping("/getSystemRoleDisPage")
    public ModelAndView getSystemRoleDisPage(@RequestParam(value = "roleId", required = false) String roleIdParam) {

        Long roleId = StringConverters.ToLong(roleIdParam);

        SystemRole systemRole = null;
        if (roleId != null) {
            systemRole = systemRoleBiz.findModel(roleId);
        }

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/system/systemRole/systemRoleDisPart");
        modelAndView.addObject("systemRole", systemRole);
        return modelAndView;
    }

    /**
     * 获取详情页面
     */
    @RequestMapping("/getSystemRoleViewPage")
    public ModelAndView getSystemRoleViewPage(@RequestParam(value = "roleId", required = false) String roleIdParam) {

        Long roleId = StringConverters.ToLong(roleIdParam);

        SystemRole systemRole = null;
        if (roleId != null) {
            systemRole = systemRoleBiz.findModel(roleId);
        }

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/system/systemRole/systemRoleViewPart");
        modelAndView.addObject("systemRole", systemRole);
        return modelAndView;
    }

    /**
     * 获取编辑页面
     */
    @RequestMapping("/getSystemRoleEditPage")
    public ModelAndView getSystemRoleEditPage(@RequestParam(value = "roleId", required = false) String roleIdParam) {

        Long roleId = StringConverters.ToLong(roleIdParam);

        SystemRole systemRole = null;
        if (roleId != null) {
            systemRole = systemRoleBiz.findModel(roleId);
        }

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/system/systemRole/systemRoleEditPart");
        modelAndView.addObject("systemRole", systemRole);
        return modelAndView;
    }

    /**
     * 执行提交的新增或修改请求
     */
    @RequestMapping("/executeSystemRoleEdit")
    @ResponseBody
    public ResultDto executeSystemRoleEdit(SystemRole systemRole,
                                           @RequestParam(value = "enabled1", required = false) String enabled,
                                           @RequestParam(value = "treesData", required = false) List<String> treesData,
                                           @RequestParam(value = "select_enterprise[]", required = false) List<String> enterprises) {
        if (CollectionUtils.isNotEmpty(enterprises))
            systemRole.setEnterprise(enterpriseBiz.findModel(StringConverters.ToLong(enterprises.get(0))));
        if (systemRole.getEnterprise() == null) {
            return ResultUtil.error("请选择企业");
        }
        //判断角色名是否重复
        if (systemRoleBiz.existRoleName(systemRole)) {
            return ResultUtil.error("您输入的角色名为空或已存在，请重新输入");
        }
        systemRole.setEnabled("true".equals(enabled));
        systemRoleBiz.addOrUpdate(systemRole);
        //将所有的权限删除，将现在的权限加上
        systemRoleBiz.removeAuth(systemRole.getId());
        systemRoleBiz.addAuth(systemRole.getId(), treesData);
        return ResultUtil.success();
    }

    /**
     * 逻辑删除机构用户信息
     */
    @RequestMapping("/logicRemoveSystemRole")
    @ResponseBody
    public JSONObject logicRemoveSystemRole(@RequestParam(value = "roleId", required = false) String roleIdParam,
                                            @RequestParam(value = "isFakeDelete", required = false) String isFakeDelete) {

        Long roleId = StringConverters.ToLong(roleIdParam);

        List<SystemUser> systemUserList = this.systemUserBiz.findByRoleId(roleId);
        List<SystemAuthority> systemAuthorityList = this.systemAuthorityBiz.getAuthoritiesByRoleId(roleId);

        if (CollectionUtils.isEmpty(systemUserList) && CollectionUtils.isEmpty(systemAuthorityList)) {
            systemRoleBiz.delete(roleId);
            return ResultJson.OK();
        }

        return ResultJson.Error("删除失败!");
    }


    /**
     * 获取角色-选择框
     */
    @RequestMapping("/getSystemRoleListMagic")
    @ResponseBody
    public List<SelectVO> getSystemRoleListMagic(@RequestParam(value = "q", required = false) String q,
                                                 @RequestParam(value = "id", required = false) String id) {
        List<SelectVO> selectVOS = new ArrayList<>();
        SystemRole role = systemRoleBiz.findModel(StringConverters.ToLong(id));
        if (role != null) {
            selectVOS.add(new SelectVO(role.getRoleName(), role.getId() + ""));
        }
        QueryParam queryParam = new QueryParam(1, 20);
        queryParam.getSqlMap().put("magicLike", q);
        queryParam.getSqlMap().put("magicId", id);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        queryParam.getSqlMap().put("enterpriseId", enterprise == null ? "-1" : enterprise.getId() + "");
        List<SystemRole> systemRoles = systemRoleBiz.findList(queryParam);
        systemRoles.forEach(systemRole -> selectVOS.add(new SelectVO(systemRole.getRoleName(), systemRole.getId() + "")));
        return selectVOS;
    }

    /**
     * 批量调整角色页面
     */
    @RequestMapping("/getRoleBatchEditPart")
    public ModelAndView getRoleBatchEditPart() {
        return new ModelAndView("pages/system/systemRole/roleBatchEditPart");
    }

    /**
     * 保存批量修改的角色
     *
     * @param organizations
     * @param positions
     * @param roles
     * @param enterprises
     * @return
     */
    @RequestMapping("/executeUserRoleBatch")
    @ResponseBody
    public ResultDto executeUserRoleBatch(@RequestParam(value = "select_organization[]", required = false) List<String> organizations,
                                          @RequestParam(value = "select_position[]", required = false) List<String> positions,
                                          @RequestParam(value = "select_role[]", required = false) List<String> roles,
                                          @RequestParam(value = "select_enterprise[]", required = false) List<String> enterprises) {

        Organization organization = null;
        Position position = null;
        SystemRole role = null;
        Enterprise enterprise = null;
        if (CollectionUtils.isNotEmpty(organizations)) {
            organization = organizationBiz.findModel(StringConverters.ToLong(organizations.get(0)));
        }
        if (CollectionUtils.isNotEmpty(positions)) {
            position = positionBiz.findModel(StringConverters.ToLong(positions.get(0)));
        }
        if (CollectionUtils.isNotEmpty(roles)) {
            role = systemRoleBiz.findModel(StringConverters.ToLong(roles.get(0)));
        }
        if (CollectionUtils.isNotEmpty(enterprises))
            enterprise = enterpriseBiz.findModel(StringConverters.ToLong(enterprises.get(0)));
        return systemRoleBiz.changeRoleBatch(organization, position, role, enterprise);
    }
    // ******************************************************************************
    // ******************************* 代码自动生成结束 *******************************
    // ******************************************************************************
}